package com.jiaai.web.gift;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jiaai.auth.model.AccessUser;
import com.jiaai.exception.ServerException;
import com.jiaai.filter.aop.TokenIntercept;
import com.jiaai.gift.api.ICarApi;
import com.jiaai.member.api.IWalletAPI;
import com.jiaai.util.RequestUtils;
import com.jiaai.util.RestResultGenerator;
import com.jiaai.util.code_pack.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * class_name:ZCarController
 * describe:TODO
 * create_user:张昉平
 * create_date:2017/12/27
 * create_date:16:17
 */
@RestController
@RequestMapping("/api/v1/app/car")
public class ZCarController {

    private static final Logger xlog = LoggerFactory.getLogger(ZCarController.class);

    @Reference
    private ICarApi iCarApi;
    @Reference
    private IWalletAPI iWalletAPI;

    @PostMapping("/buy")
    @TokenIntercept(checkVisitor = true)
    public Object buy(@RequestParam Integer carId)throws ServerException {
        AccessUser user = RequestUtils.getUser();
        try {
            if (iCarApi.checkHadTheCar(carId, user.getUserId())) return RestResultGenerator.genErrorResult(ErrorCode.ALRERDY_CAR, "您已经拥有该座驾啦!");
            BigDecimal money = iWalletAPI.getMyMoney(user.getUserId());
            BigDecimal price = iCarApi.getPrice(carId);
            if (money.compareTo(price) == -1)return RestResultGenerator.genErrorResult(ErrorCode.NOT_ENOUGH_MONEY, "大爷的, 余额不足,请充值!");

            String res = iCarApi.buyCar(carId, user.getUserId());

            if (res.equals("CANNOT")) return RestResultGenerator.genErrorResult(ErrorCode.CAR_CANNOT, "大爷的, 你不能够买该vip座驾");

            return  RestResultGenerator.genSuccessResult(res);
        }catch (Exception e){
            e.printStackTrace();
            xlog.error("购买者: ".concat(user.getUserId())+"\t"+", 座驾id: "+carId);
            return RestResultGenerator.genErrorResult("服务器异常");
        }
    }
    
}
